package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.PostDao;
import com.example.simpleforum.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 删除帖子Servlet
 */
public class PostDeleteServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取帖子ID
        String postIdStr = request.getParameter("id");
        if (postIdStr == null || postIdStr.trim().isEmpty()) {
            // 帖子ID为空，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
            return;
        }
        
        try {
            int postId = Integer.parseInt(postIdStr);
            
            // 删除帖子（确保是帖子作者）
            PostDao postDao = new PostDao();
            boolean success = postDao.deletePost(postId, user.getId());
            
            if (success) {
                // 删除成功，重定向到帖子列表页面
                response.sendRedirect(request.getContextPath() + "/PostListServlet");
            } else {
                // 删除失败（可能是帖子不存在或无权删除）
                response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postId);
            }
        } catch (NumberFormatException e) {
            // 帖子ID格式错误，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // POST请求也执行相同操作
        doGet(request, response);
    }
}